package com.sora.pet.service.impl;

import com.sora.basic.exception.BusinessException;
import com.sora.basic.service.IBaiduAiAuditService;
import com.sora.basic.util.*;
import com.sora.order.domain.OrderPetAcquisition;
import com.sora.order.mapper.OrderPetAcquisitionMapper;
import com.sora.org.domain.Employee;
import com.sora.org.domain.Shop;
import com.sora.org.mapper.EmployeeMapper;
import com.sora.org.mapper.ShopMapper;
import com.sora.pet.domain.SearchMasterMsg;
import com.sora.pet.domain.SearchMasterMsgAuditLog;
import com.sora.pet.dto.MsgDto;
import com.sora.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.sora.pet.mapper.SearchMasterMsgMapper;
import com.sora.pet.query.SearchMasterMsgQuery;
import com.sora.pet.service.ISearchMasterMsgService;
import com.sora.basic.service.impl.BaseServiceImpl;
import com.sora.user.domain.Logininfo;
import com.sora.user.domain.User;
import com.sora.user.mapper.LogininfoMapper;
import com.sora.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;



    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {

        //1.添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);

        //2.百度AI智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());

        if(boo1 && boo2){//百度AI智能审核通过
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.save(log);

            //查找最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            List<Shop> shops = shopMapper.loadAll();
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if(nearestShop != null){//代表50公里内有离用户最近的店铺
                msg.setShopId(nearestShop.getId());
                //给店铺发消息
                //SmsUtils.sendSms(nearestShop.getTel(),"您有最新的订单，请前往"+msg.getAddress()+"接回宠物");
                System.out.println("您有最新的订单，请前往"+msg.getAddress()+"接回宠物");
            }else{////代表50公里内没有离用户最近的店铺
                msg.setState(3);//放入寻主池
                //给用户发消息
                //SmsUtils.sendSms(user.getPhone(),"抱歉！你周围没有可用的店铺。");
                System.out.println("抱歉！你周围没有可用的店铺。");
            }
            searchMasterMsgMapper.update(msg);
            return new AjaxResult();
        }else{//百度AI智能审核没有通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);

            //发消息给用户
            //SmsUtils.sendSms(user.getPhone(),"你填入的寻主消息不合规，请重新填入！");
            System.out.println("你填入的寻主消息不合规，请重新填入！");

            //删除msg
            searchMasterMsgMapper.del(msg.getId());
            return new AjaxResult(false,"你填入的寻主消息不合规，请重新填入！");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query,HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query,HttpServletRequest request) {
        //设置状态为完成
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        Long shop_id = employee.getShop_id();
        if(shop_id != null){//店铺管理员在查询
            query.setShopId(shop_id);
        }
        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query,HttpServletRequest request) {
        //设置状态为寻主池
        query.setState(3);

        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query,HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        Long shop_id = employee.getShop_id();
        if(shop_id != null){//店铺管理员在查询
            query.setShopId(shop_id);
        }
        return super.pageQuery(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(MsgDto msgDto) {
        //判断订单是否存在
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());
        if(order != null && order.getState() == 0){
            throw new BusinessException("订单正在处理，请勿重复接单！");
        }

        //生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition newOrder = creatOrder(msg,msgDto);
        orderPetAcquisitionMapper.save(newOrder);


        //向员工发送接收宠物的短信
        Employee employee = employeeMapper.loadById(msgDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请前往"+msg.getAddress()+"接收宠物！");
        System.out.println("你有新的订单，请前往"+msg.getAddress()+"接收宠物！");
    }

    private OrderPetAcquisition creatOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        //order.setState(0);
        order.setPrice(msg.getPrice());
        //order.setPaytype(0);
        //order.setPetId();
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());

        return order;
    }
}
